package com.example.demo.generator.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.example.demo.generator.entiy.TMenu;
import com.example.demo.generator.entiy.TUser;
import com.example.demo.generator.entiy.menuclass;
import com.example.demo.generator.entiy.meta;
import com.example.demo.generator.service.TMenuService;
import com.example.demo.generator.service.TUserService;
import com.example.demo.generator.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.omg.PortableInterceptor.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("menu")
@CrossOrigin("*")
@Api(tags = "菜单接口")
public class MenuController {
    @Autowired
    public JwtUtil jwtUtil;
    @Autowired
    public TMenuService tMenuService;

    @Autowired
    public TUserService tUserService;

    @ApiOperation("获取全部菜单")
    @GetMapping("getmenulist")
    //获取菜单列表
    public R getmenulist(){
        List<menuclass>menuclassList=new ArrayList<>();
        QueryWrapper<TMenu>tMenuQueryWrapper=new QueryWrapper<>();
        tMenuQueryWrapper.eq("enabled",1);  //可用
        tMenuQueryWrapper.eq("pid",0);
        List<TMenu>pmenulist=tMenuService.list(tMenuQueryWrapper);
        for(int i=0;i<pmenulist.size();i++){
            menuclass c=new menuclass();
            c.setId(pmenulist.get(i).getId());
            c.setPath(pmenulist.get(i).getPath());
            c.setName(pmenulist.get(i).getName());
            meta m=new meta();
            m.setTitle(pmenulist.get(i).getTitle());
            m.setIcon(pmenulist.get(i).getIcon());
            c.setMeta(m);

            getchild(c);

            menuclassList.add(c);
        }
        return R.ok(menuclassList);
    }

    //递归获取
    public void getchild(menuclass menu){
        if(haschild(menu.getId())){
            //存在下一级
            List<menuclass>menuclassList=new ArrayList<>();
            QueryWrapper<TMenu>tMenuQueryWrapper=new QueryWrapper<>();
            tMenuQueryWrapper.eq("enabled",1);  //可用
            tMenuQueryWrapper.eq("pid",menu.getId());
            List<TMenu>pmenulist=tMenuService.list(tMenuQueryWrapper);
            for(int i=0;i<pmenulist.size();i++){
                menuclass c=new menuclass();
                c.setId(pmenulist.get(i).getId());
                c.setPath(pmenulist.get(i).getPath());
                c.setName(pmenulist.get(i).getName());
                meta m=new meta();
                m.setTitle(pmenulist.get(i).getTitle());
                c.setMeta(m);
                menuclassList.add(c);

                getchild(c);
            }
            menu.setChildren(menuclassList);
        }
        //不存在，推出递归
    }

    //判断是否存在下一级
    public boolean haschild(Integer id){
        QueryWrapper<TMenu>tMenuQueryWrapper=new QueryWrapper<>();
        tMenuQueryWrapper.eq("pid",id);
        tMenuQueryWrapper.eq("enabled",1);
        List<TMenu>menuList=tMenuService.list(tMenuQueryWrapper);
        if(menuList.size()>0){
            return true;
        }else{
            return  false;
        }
    }

    @ApiOperation(value="获取用户菜单")
    @GetMapping("getusermenu")
    //获取用户菜单
    public R getusermenu(HttpServletRequest request){
        //获取token中userid
        String token=request.getHeader("token");
        TUser tUser=jwtUtil.getuser(token);
        //从token中获取用户id，查询该Id的用户是否存在，存在则token验证通过

        List<menuclass>menuclassList=new ArrayList<>();
        //获取用户角色
        List<TMenu>tMenuList=tUserService.getusermenu(tUser.getId());
        for(int i=0;i<tMenuList.size();i++){
            menuclass c=new menuclass();
            c.setId(tMenuList.get(i).getId());
            c.setPath(tMenuList.get(i).getPath());
            c.setName(tMenuList.get(i).getName());

            meta m=new meta();
            m.setTitle(tMenuList.get(i).getTitle());
            m.setIcon(tMenuList.get(i).getIcon());
            c.setMeta(m);
            //menuclassList.add(c);
            //获取上级
            getparent(c,menuclassList);
        }
        //查找上级
        return R.ok(menuclassList);
    }

    //递归查找上一级
    public void getparent(menuclass menu,List<menuclass>menuclassList){
        if(hasparent(menu.getId())){

            TMenu tMenu=tMenuService.getById(menu.getId());
            TMenu pmenu=tMenuService.getById(tMenu.getPid());
            //检查是否已经存在父级，存在的话，就直接赋值，如果不存在，新建父级节点
            if(getparentnode(pmenu.getId(),menuclassList)==null) {
                menuclass m = new menuclass();
                m.setId(pmenu.getId());
                m.setPath(pmenu.getPath());
                m.setName(pmenu.getName());
                meta meta = new meta();
                meta.setTitle(pmenu.getTitle());
                meta.setIcon(pmenu.getIcon());
                m.setMeta(meta);
                List<menuclass> childlist = new ArrayList<>();
                childlist.add(menu);
                m.setChildren(childlist);
                menuclassList.add(m);
                getparent(m,menuclassList);
            }else{
                menuclass m=getparentnode(pmenu.getId(),menuclassList);
                m.getChildren().add(menu);
                getparent(m,menuclassList);
            }
        }else{
            if(!menuclassList.contains(menu)) {
                menuclassList.add(menu);
            }
        }
    }

    //判断是否存在上级
    public boolean hasparent(Integer id){
        QueryWrapper<TMenu>tMenuQueryWrapper=new QueryWrapper<>();
        tMenuQueryWrapper.eq("id",id);
        tMenuQueryWrapper.eq("enabled",1);
        tMenuQueryWrapper.gt("pid",0);
        List<TMenu>tMenuList=tMenuService.list(tMenuQueryWrapper);
        if(tMenuList.size()>0){
            return true;
        }
        else{
            return false;
        }
    }

    //判断是否存在父级节点
    public menuclass getparentnode(Integer id,List<menuclass>menuclassList){
        menuclass existmenuclass=null;
        for(int i=0;i<menuclassList.size();i++){
            if(menuclassList.get(i).getChildren()!=null){
                if(menuclassList.get(i).getId()==id){
                    existmenuclass= menuclassList.get(i);
                }
            }
        }
        return existmenuclass;
    }

    //菜单的增、删、改、查

    @PostMapping("insertmenu")
    @ApiOperation("添加菜单")
    public R insertmenu(@RequestBody TMenu menu){
        try{
            tMenuService.save(menu);
            return R.ok(menu);
        }
        catch (Exception ex){
            return R.failed(ex.toString());
        }
    }

    @PostMapping("editmenu")
    @ApiOperation("编辑菜单")
    public R editmenu(@RequestBody TMenu menu){
        try{
            tMenuService.updateById(menu);
            TMenu tMenu=tMenuService.getById(menu.getId());
            return R.ok(tMenu);
        } catch (Exception ex) {
            return R.failed(ex.toString());
        }
    }

    @GetMapping("deletemenu")
    @ApiOperation("删除菜单")
    public R deletemenu(@RequestParam("id") Integer id) {
        try {
            TMenu tMenu = tMenuService.getById(id);
            tMenu.setEnabled(0);
            tMenuService.updateById(tMenu);

            //循环删除子级菜单
            deletechild(tMenu);
            return R.ok("success");
        } catch (Exception ex) {
            return R.failed(ex.toString());
        }
    }

    public void deletechild(TMenu tMenu){
        if(haschild(tMenu.getId())){
            QueryWrapper<TMenu>tMenuQueryWrapper=new QueryWrapper<>();
            tMenuQueryWrapper.eq("pid",tMenu.getId());
            List<TMenu> tMenuList=tMenuService.list(tMenuQueryWrapper);
            if(tMenuList.size()>0) {
                for(int i=0;i<tMenuList.size();i++){
                    tMenuList.get(i).setEnabled(0);
                    tMenuService.updateById(tMenuList.get(i));

                    deletechild(tMenuList.get(i));
                }
            }

        }
    }
}
